package com.gosling.cloudspace.aop;

import cn.hutool.core.collection.CollectionUtil;
import com.gosling.cloudspace.common.annotation.TrimAndDic;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 去掉字符串的首尾空格
 *
 * @author lihonglin
 * @date 2023/4/23 15:01
 */
public class TrimAndDicAspect {

    public static final Logger logger = LoggerFactory.getLogger(TrimAndDicAspect.class);
    public static final List<String> IGNORE_LIST = Arrays.asList("serialVersionUID", "id");

    public static void trimOrAddZero(Object obj) throws Exception {
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                //去除private权限，变为可更改
                field.setAccessible(true);
                if (IGNORE_LIST.contains(field.getName())) {
                    continue;
                }
                String name = field.getName();
                Object invoke = new PropertyDescriptor(name, clazz).getReadMethod().invoke(obj);
                String value = Objects.nonNull(invoke) ? invoke.toString().trim() : "";
                //对字符串类型字段进行trim处理
                if (field.getType() == String.class) {
                    if (StringUtils.isNotBlank(value)) {
                        //在原有的对象上设置去除首尾空格的新值
                        field.set(obj, invoke.toString().trim());
                    }
                }
                //对数据字典的字段需要补齐0的进行处理
                if (field.isAnnotationPresent(TrimAndDic.class)) {
                    TrimAndDic annotation = field.getAnnotation(TrimAndDic.class);
                    String type = annotation.type();
                    //数据字典匹配
                    String dic = annotation.dictionary();
                    String fieldName = annotation.fieldName();
                    List<String> dictionaryList = Arrays.asList(dic.split(","));
                    //是否是按逗号分割
                    if (TrimAndDic.LIST.equalsIgnoreCase(type)) {
                        List<String> valueList = Arrays.asList(value.split(","));
                        if (CollectionUtil.isEmpty(valueList)) {
                            continue;
                        }
                        StringBuilder fieldValue = new StringBuilder();
                        for (String dicValue : valueList) {
                            if (StringUtils.isBlank(dicValue)) {
                                continue;
                            }
                            if (!dictionaryList.contains(dicValue)) {
                                fieldValue.append(getNewValue(dicValue, annotation, dic, dictionaryList)).append(",");
                            } else {
                                fieldValue.append(dicValue).append(",");
                            }
                        }
                        if (fieldValue.length() != 0) {
                            Set a = new HashSet(Arrays.asList(fieldValue.toString().split(",")));
                            a.removeAll(new HashSet(dictionaryList));
                            if (a.size() > 0) {
                                throw new Exception("[" + fieldName + "]字段值非法,当前值[" + value + "]应填[" + dic + "]");
                            }
                            fieldValue.insert(0, ",");
                            field.set(obj, fieldValue.toString());
                        }
                    } else {
                        if (StringUtils.isBlank(value)) {
                            continue;
                        }
                        if (StringUtils.isNotBlank(value) && !dictionaryList.contains(value)) {
                            field.set(obj, getNewValue(value, annotation, dic, dictionaryList));
                        }
                    }
                }
            } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
                logger.error("字段获取异常！");
                logger.error(e.getMessage(), e);
            } catch (Exception e) {
                logger.error("字段获取异常！");
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
    }

    private static String getNewValue(String value, TrimAndDic annotation, String dic, List<String> dictionaryList) throws Exception {
        String fieldName = annotation.fieldName();
        if (!dictionaryList.contains(TrimAndDic.ZERO + value) && !dictionaryList.contains(value.substring(1))) {
            throw new Exception("[" + fieldName + "]字段值非法,当前值[" + value + "]应填[" + dic + "]");
        }
        if (dictionaryList.contains(TrimAndDic.ZERO + value)) {
            return TrimAndDic.ZERO + value;
        }
        if (dictionaryList.contains(value.substring(1))) {
            return value.substring(1);
        }
        return null;
    }

}
